﻿using Microsoft.Extensions.Primitives;
using System.Linq;
using System.Text.Json;
using System.Text;
using Newtonsoft.Json.Linq;

namespace WebAppFilterDemo.Middleware;

public class AddParametersMiddleware
{
    private readonly RequestDelegate _next;

    public AddParametersMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await Console.Out.WriteLineAsync(" AddParametersMiddleware - Invoke ");
        if (context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase) &&
            context.Request.ContentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) == true)
        {
            // 读取请求体
            using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8))
            {
                var requestBody = await reader.ReadToEndAsync();

                // 将 JSON 转换为 JObject
                var jsonObject = JObject.Parse(requestBody);

                // 添加额外的参数
                var appId = "91";
                var tenantId = "1001";

                // 设置新的属性
                jsonObject.Add("appId", appId);
                jsonObject.Add("tenantId", tenantId);

                // 修改后的 JSON 字符串
                var modifiedJson = jsonObject.ToString();

                // 将修改后的 JSON 放回请求体
                var modifiedBytes = Encoding.UTF8.GetBytes(modifiedJson);
                context.Request.Body = new MemoryStream(modifiedBytes);
            }
        }

        await _next(context);
    }
}

// 扩展方法用于注册中间件
public static class AddParametersMiddlewareExtensions
{
    public static IApplicationBuilder UseAddParametersMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<AddParametersMiddleware>();
    }
}














//public async Task Invoke(HttpContext context)
//{
//    if (context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
//    {
//        //// 使用 Form 属性添加额外的参数
//        //context.Request.Form = new FormCollection(context.Request.Form.ToDictionary(kvp => kvp.Key, kvp => kvp.Value), new FormFileCollection());

//        //// 添加额外的参数
//        //context.Request.Form.Append("appId", "your_app_id");
//        //context.Request.Form.Append("tenantId", "your_tenant_id");

//        // 使用 Form 属性添加额外的参数
//        var formDictionary = new Dictionary<string, StringValues>(context.Request.Form.ToDictionary(kvp => kvp.Key, kvp => kvp.Value));
//        formDictionary.Add("appId", "your_app_id");
//        formDictionary.Add("tenantId", "your_tenant_id");
//        context.Request.Form = new FormCollection(formDictionary);
//    }

//    await _next(context);
//}
